package com.zrz.util;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;

/**
 * @author liuyang
 * @since 2018/6/28 14:57
 */
public class ExcelUtil {

    public static Workbook readExcel(String filename, InputStream is){
        Workbook wb = null;
        String extString = filename.substring(filename.lastIndexOf("."));
        try {
            if (".xls".equals(extString)){
                wb = new HSSFWorkbook(is);
            }else if (".xlsx".equals(extString)){
                wb = new XSSFWorkbook(is);
            }else {
                wb = null;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return wb;
    }

    public static Object getCellFormatValue(Cell cell){
        DecimalFormat df = new DecimalFormat("#");
        Object cellValue = null;
        if(cell!=null){
            //判断cell类型
            switch(cell.getCellTypeEnum()){
                case STRING:{
                    cellValue = String.valueOf(cell.getStringCellValue());
                    break;
                }
                case NUMERIC:{
                    cellValue = String.valueOf(df.format(cell.getNumericCellValue()));
                    break;
                }
                default:
                    cellValue = "";
            }
        }else{
            cellValue = "";
        }
        return cellValue;
    }

}
